<template>
  <el-dialog :model-value="show" :title="editId == 0 ? '添加用户' : '编辑用户'" @closed="closeFn">
    <el-form :model="formData" ref="formRef" :rules="rules" label-width="120px">
      <el-form-item label="账号" prop="username">
        <el-input v-model="formData.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="姓名" prop="nickName">
        <el-input v-model="formData.nickName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" type="password" autocomplete="off" :disabled="editId != 0" />
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input v-model="formData.note" type="textarea" :row="3" autocomplete="off" />
      </el-form-item>
      <el-form-item label="是否启用">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1" size="large">是</el-radio>
          <el-radio :label="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeFn">取消</el-button>
        <el-button type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang='ts'>
import { reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { registerUserApi, getUserInfoByIdApi, updateUserInfoApi } from '@/api'
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  editId: {
    type: Number,
    default: 0
  }
})
const emit = defineEmits(['closed'])

const validatePass = (rule: any, value: any, callback: any) => {
  if (/\s/.test(value)) {
    callback(new Error('密码中不能包含空格'))
  } if (!/[0-9]/.test(value)) {
    callback(new Error('密码中至少要有一个数字'))
  } else if (!/[a-zA-Z]/.test(value)) {
    callback(new Error('密码中至少要有一个字母'))
  } else {
    callback()
  }
}

const formRef = ref<FormInstance>();
const rules = ref<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    // { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
    // { validator: validatePass, trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  note: [
    { type: 'string', message: '请输入备注', trigger: 'blur' },
  ]
})

const formData = reactive<IUserModel>({
  username: '',
  nickName: '',
  email: '',
  password: '',
  note: '',
  status: 1
})

const submit = () => {

  formRef.value?.validate((valid) => {
    if (valid) {
      if (props.editId == 0) {
        ElMessageBox.confirm('确定要提交吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
          // 提交表单 ， 发送请求
          registerUserApi(formData).then(res => {
            if (res.code === 200) {
              ElMessage.success('新增用户成功')
              // 清空表单
              formRef.value?.resetFields();
              // 关掉弹出层
              // 刷新表格数据
              emit('closed', true)
            }
          })
        })
      } else {
        // editId 不为0 ， 表示是要更新数据
        ElMessageBox.confirm('确定要提交吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
          // 提交表单 ， 发送请求
          updateUserInfoApi(formData).then(res => {
            if (res.code === 200) {
              ElMessage.success('更新用户成功')
              // 清空表单
              formRef.value?.resetFields();
              // 关掉弹出层
              // 刷新表格数据
              emit('closed', true)
            }
          })
        })

      }
    }
  })
}

const closeFn = () => {
  // 通知父组件，当前的这个组件已经被关闭了
  emit('closed');
  formRef.value?.resetFields();
}

// 编辑修改用户数据
// 下面

// 进入组件的时候需要先请求旧的数据回来
// 如果 editId 不是 0 我们点的是编辑按钮
// 我们希望当editId变化的时候再请求
watch(() => props.editId, (val) => {
  if (val !== 0) {
    getUserInfoByIdApi(props.editId).then(res => {
      if (res.code == 200) {
        Object.assign(formData, res.data);
      }
    })
  }
})

</script>
<style lang="less" scoped></style>